 <head>
    <link rel="icon" type="image/vnd.microsoft.icon" href="images/bridge.ico">
	<link rel="stylesheet" href="styles/screen.css" type="text/css" media="screen, projection">
	<link rel="stylesheet" href="styles/print.css" type="text/css" media="print">	
	<!--[if lt IE 8]><link rel="stylesheet" href="styles/ie.css" type="text/css" media="screen, projection"><![endif]-->
	<link type="text/css" href="styles/jquery-ui-1.8.1.custom.css" rel="stylesheet" />	
	<link rel="stylesheet" href="styles/gb.css" type="text/css" media="screen">
	<link rel="stylesheet" type="text/css" href="scripts/jsonwidget.css" />
    <script type="text/javascript" src="scripts/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="scripts/jquery-ui-1.8.1.custom.min.js"></script>
    <script type="text/javascript" src="scripts/underscore-min.js"></script>
	<script type="text/javascript" src="scripts/wikid-0.2.js"></script>
	<script type="text/javascript" src="scripts/jquery.parsequery.js"></script>
	<script type="text/javascript" src="scripts/showdown.js"></script>
	<script type="text/javascript" src="scripts/jsonpath-0.8.0.js"></script>	 
	 <script type="text/javascript" src="scripts/jquery.corner.js"></script>
	 <script type="text/javascript" src="scripts/couch.js"></script> 
	 <script type="text/javascript" src="scripts/futon.format.js"></script> 
	 <script type="text/javascript" src="scripts/jquery.couch.js"></script> 
	 <script type="text/javascript" src="scripts/jquery.suggest.js"></script> 
	 <script type="text/javascript" src="scripts/jquery.timeago.js"></script>
	 <script type="text/javascript" src="scripts/jquery.clickmenu.pack.js"></script>
	 <script type="text/javascript" src="scripts/jsonedit.js"></script>
	 <script type="text/javascript" src="scripts/json.js"></script>
	 <script type="text/javascript">
	    $(function() {
			var db_name = wikid.parseDBname(window.location);
			var wikid_id = wikid.parseTopicName(window.location);

			var db = new CouchDB(db_name, {"X-Couch-Full-Commit":"true"});
			var doc = db.open(wikid_id);
            var result;
			var isNew = false;
            if (doc) {
                result = wikid.toWikid(doc, db, 'edit');
            } else {
				isNew = true;
                // it is a new document
                doc = {};
                result = {};
                result.doc = doc;
                result.topic = 'New Topic';
                result.title = 'New Topic';
                result.isNew = true;
                if (wikid_id) {
                    result.doc._id = wikid_id;
                }

				
            }


			$('.readableId').text(result.topic);
			document.title = 'Editing ' + result.title;
			$('#wikid_id').val(result.doc._id);
			$('#wikiTextarea').val(result.doc['-wiki']);
			var tags = result.doc['-tags'];

			var current_tag;

			
			// add any tags 
			var tagsToAdd = wikid.parseTagsToAdd(window.location);
			wikid.addTags(result, tagsToAdd, db);
            if (isNew){
                wikid.loadInstanceScripts(result, 'scripts', 'edit');
            }


			
			if (result.doc['-tags']) {
				$.each(result.doc['-tags'], function(i, tag) {
					current_tag = tag;
                    var readable = wikid.titleFromTopicId(tag);
					var anchor = $('<a href="#' + tag +'" class="tag">' + readable + '</a><span class="ui-icon ui-icon-close">Remove Tab</span>');

					anchor.click(function() {
                            
							showTag(tag);
					});
					var tab = $('<li></li>');
                    tab.data('tag', tag);
					tab.append(anchor);
					$('#instanceTabsUL').append(tab);

                    var tinyDiv = $('<div id="' + tag +'" class="one_px"></div>');
                    $('#instanceTabs').append(tinyDiv);

				});
			} else {
    
                $('field_editor_wrap').hide();
            }

            /******************* All to do with + button ****************/
            // add a '+' tab to add tags
            var anchor = $('<a href="#addTagButton" class="tag" title="Add Tag" >+</a>');
            anchor.click(function() {
                setTimeout(openAddDialog, 200);
                return false;
            });

            function openAddDialog() {
                $("#dialog-add-tag").dialog('open');
                $('#dialog-add-tag input').focus();
            }

            var tab = $('<li></li>');
            tab.append(anchor);
            $('#instanceTabsUL').append(tab);
            var tinyDiv = $('<div id="addTagButton" class="one_px"></div>');
            $('#instanceTabs').append(tinyDiv);

            // the '+' dialog
            $("#dialog-add-tag").dialog({
                autoOpen: false,
                height: 140,
                modal: true
		    });
            // search
			$('#dialog-add-tag input').suggest(function(text, callback) {
				$.getJSON("/" + db_name + "/_all_docs?startkey=%22"+ text +"%22&endkey=%22"+ text +"zzz%22&limit=10&callback=?", function(docs){
					  var matches = [];
					  for (var i = 0; i < docs.rows.length; i++) {
						if (docs.rows[i].id.indexOf(text) == 0) {
						  matches[i] = docs.rows[i].id;
						}
					  }
					  callback(matches);
				});
			}).keypress(function(e) {
				if (e.keyCode == 13) {
                    finishAdd();
				}
			});
            $('#finishAdd').click(finishAdd);

            function finishAdd() {
                $("#dialog-add-tag").dialog('close');
                var tag = $('#dialog-add-tag input').val();
                current_tag = tag;
                var readable = wikid.titleFromTopicId(tag);
                var anchor = $('<a href="#' + tag +'" class="tag">' + readable + '</a><span class="ui-icon ui-icon-close" title="Remove Tag">Remove Tag</span>');

                anchor.click(function() {

                        showTag(tag);
                    
                });
                var tab = $('<li></li>');
                tab.data('tag', tag);
                tab.append(anchor);
                $('#instanceTabsUL').append(tab);

                var tinyDiv = $('<div id="' + tag +'" class="one_px"></div>');
                $('#instanceTabs').append(tinyDiv);
                var length = $('#instanceTabs').tabs('length') -1;
                $('#instanceTabs').tabs('remove', length);

   
                // get any instance info
                wikid.addTags(result, [tag], db);



                $('#dialog-add-tag input').val('');
            }

            /******************* End of All to do with + button ****************/


            // remove tags when the x is clicked
            $('#instanceTabs span.ui-icon-close').live('click', function() {
                if (confirm('Are you sure you want to remove this tag?')) {
                    var tagToRemove = $(this).parent().data('tag');
                    var index = $('li',$('#instanceTabs')).index($(this).parent());
                    $('#instanceTabs').tabs('remove', index);
                    doc['-tags'] = $.grep(doc['-tags'], function(value) {
                        return value != tagToRemove;
                    });
                }

		    });



			$('#instanceTabs').tabs();
			

			
			var je;
			
			function saveShownTag(){

                if (je) {
                    je.updateJSON();
                    doc[current_tag] = JSON.parse($('#je_sourcetextarea').val());
                }

				$('#je_sourcetextarea').val(null);
			}
			
			function showTag(next_tag) {
				if (next_tag != current_tag) {
					saveShownTag();
				}
				current_tag = next_tag;

                var instanceInfo = result.instanceInfos[current_tag];
                if (instanceInfo && instanceInfo.schema) {
                    $('#field_editor').show();
                    var tag_value = doc[next_tag];
                    if (tag_value) {
                        $('#je_sourcetextarea').val(JSON.stringify(tag_value));

                    } else {
                        $('#je_sourcetextarea').val('');
                    }

                    $('#je_schematextarea').val(JSON.stringify(instanceInfo.schema));
                    je=new jsonwidget.editor();
                    je.setView('form');
                    // hide the buttons
                    $('#je_formbutton').hide();
                    $('#je_sourcebutton').hide();
                } else {
                    $('#field_editor').hide();
                }
					

			}
			
			$(".save")
				.button()
				.click(function() {
					
					doc._id = $('#wikid_id').val();					
					doc['-wiki'] = $('#wikiTextarea').val();
					if (je) {
						saveShownTag();
					}
			
					var now = new Date();
					doc["-lastmodified"] = iso8601(now);

					if (doc._id != wikid_id) {
						delete doc._rev;
					}
					db.save(doc);
					
					// Renaming
					if (!isNew && (doc._id != wikid_id)) {
						var old_doc = db.open(wikid_id);
						db.deleteDoc(old_doc);
					}
					$(document).trigger("save");
					
					window.location = "topic.html?" + doc._id;
				
			})
			$('.cancel').button().click(function() {
                if (!isNew)
    				window.location = "topic.html?" + doc._id;
                else
                    window.location = "index.html";
			});
			// if it is a new, then show that tag
			var newTags = wikid.parseNewTags(window.location);
			if (newTags && newTags.length > 0) {
				var tagToShow = newTags[0];
				showTag(tagToShow);
                if (newTags.length == 1) {
                    $('#instanceTabs').hide();
                    $('#field_editor_wrap').css({'padding':'0px', 'border' : 'none'});
                }

			} else {
				// show the first field
				showTag(current_tag);
			}
			$('.button').button();

			

		});
	 </script>
  </head>
  <body>
	<div id="mainsearch" >
		<form action="topic.html">
			<input id="search" type="text" name="name" /> 
		</form>
	</div>  
	 <div class="container">
		<div class="span-24 last">
			&nbsp;
		</div>
		<div class="span-3 left">
			<img id="leftLogo" src="images/gb-logo-trim.png" />
			<a href="index.html">Dashboard</a><br/>
			<a href="topic.html?Conversation">Conversations</a><br/>
			<a href="topic.html?Project">Projects</a><br/>
			<a href="topic.html?Person">People</a><br/>
		</div>
		<div id="contentpane" class="span-20 last  neutral-1" > <!-- content pane -->
			<div class="span-20 last maintabs">	
				<ul id="tabnav"> 
					<li id="Info-tab"><a href="#" class="maintab active">Topic</a></li> 
					<li id="Audiostream-tab"><a href="#" class="maintab">Audiostream</a></li> 
				</ul>
			</div>
			<div class="span-13 ">&nbsp;</div>
			<div id="title" class="readableId padcontent span-19 last">Title</div>
			<div id="Info" class="padcontent span-19 last content-container">	
                    <div id="topicEntry">
                        <div class="header">
                            Topic
                        </div>
                        <div>
                            <input id="wikid_id" name="wikid_id" type="text" />
                        </div>
                    </div>
                	<div> <!-- Start of tag section-->
						<div id="instanceTabs">
							<ul id="instanceTabsUL">
							</ul>
						</div>
						<div id="field_editor_wrap" class="ui-widget-content">

							<div id="field_editor" style="display:none;">
								<div id="je_warningdiv">
								</div>
								<div>
									<span id="je_formbutton" style="cursor: pointer">[Edit w/Form]</span>
									<span id="je_sourcebutton" style="cursor: pointer">[Edit Source]</span>
								</div>
								<div id="je_formdiv" style="text-background: white">
								</div>
								<div>
									<div id="je_schemaformdiv" style="text-background: white">
									</div>
									<textarea id="je_schematextarea" style="display: none" rows="30" cols="80"></textarea>
									<form method='POST' id="je_sourcetextform">
										<textarea id="je_sourcetextarea" rows="30" cols="80" name="sourcearea"></textarea>
									</form>
								</div>
							</div> <!-- End of field Editor-->
						</div> <!-- End of field editor wrap -->
					</div> <!-- End of tag section -->
					<div>
						<div class="header">
							Wiki
						</div>
						<div>
							<textarea rows="10" cols="80" id="wikiTextarea"></textarea>
						</div>
					</div>

					<div class="space">
						<button class="save">Save</button>
						<button class="cancel">Cancel</button>
					</div>			
				</div> <!-- End of info -->
				
		</div> <!-- End content pane -->
	</div> <!-- End Container -->
	<div class=" footer">
		Footer
	</div>
    <div id="dialog-add-tag" title="Add A Tag">
        <p>Tag <input type="text" name="search" /> <button id="finishAdd">Add</button></p>
    </div>
	</body>
 </html>